package model

import (
	"golang.org/x/crypto/bcrypt"
	log "missC/utils/logs"
)

// User 用户表的结构体

type User struct {
	Id       int        `gorm:"column:id;type:int(11);primary_key;AUTO_INCREMENT;comment:id" json:"id"`
	Username string     `gorm:"column:username;type:varchar(100);comment:用户名" json:"username"`
	Password string     `gorm:"column:password;type:varchar(255);comment:密码" json:"password"`
	AImg     string     `gorm:"column:a-img;type:varchar(255);comment:头像" json:"a-img"`
	Phone    int        `gorm:"column:phone;type:int(11);comment:手机号" json:"phone"`
	Mail     string     `gorm:"column:mail;type:varchar(100);comment:邮箱" json:"mail"`
	Gitee    string     `gorm:"column:gitee;type:varchar(100);comment:gitee账号" json:"gitee"`
	Qq       int        `gorm:"column:qq;type:int(11);comment:qq号" json:"qq"`
	Wechat   string     `gorm:"column:wechat;type:varchar(100);comment:微信号" json:"wechat"`
	Ip       string     `gorm:"column:ip;type:varchar(255);comment:登陆ip" json:"ip"`
	Create   *LocalTime `gorm:"autoCreateTime;type:datetime;comment:创建时间" json:"create"`
	Update   *LocalTime `gorm:"autoUpdateTime;type:datetime;comment:更新时间" json:"update"`
}

// 根据gitee查询用户进行登陆
func GetGitee(gitee string) (User, int) {
	var user User

	db.Where("gitee = ?", gitee).First(&user)

	if user.Id == 0 {
		//返回用户不存在
		return user, 204
	}
	log.Info("三方登陆成功,登陆用户信息", user)
	return user, 200
}

// CheckLogin 后台登录验证
func CheckLogin(username string, password string) (User, int) {
	var user User

	db.Where("username = ?", username).First(&user)

	ok := ComparePasswords(user.Password, password)
	if user.Id == 0 {
		//返回用户不存在
		return user, 204
	}
	if !ok {
		//密码错误
		return user, 203
	}
	log.Info("登陆成功,登陆用户信息", user)
	return user, 200
}

// CheckUser 查询用户是否存在
func CheckUser(name string) (code int) {
	var user User
	db.Select("id").Where("username = ?", name).First(&user)
	if user.Id > 0 {
		return 202
	}
	return 200
}

// AddUser 注册用户
func AddUser(user User) (User, int) {

	//密码加密重新赋值
	user.Password, _ = HashPassword(user.Password)
	//创建用户
	db.Create(&user)

	log.Info("创建用户成功!", user)
	return user, 200

}

// HashPassword 使用 Bcrypt 算法生成密码哈希值
func HashPassword(password string) (string, error) {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return string(hashedPassword), nil
}

// ComparePasswords 比较输入的密码与哈希值是否匹配
func ComparePasswords(hashedPassword, password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
	return err == nil
}
